home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1995 February: Tool Chest / Dev.CD Feb 95 / Dev.CD Feb 95.toast / Sample Code / Snippets / Toolbox / Password / Sample.c < prev    next >
Encoding:
C/C++ Source or Header  |  1992-07-15  |  25.5 KB  |  738 lines  |  [TEXT/MPS ]

  1. /*------------------------------------------------------------------------------
  2. #
  3. #    This is just a hacked version of CSample.  Ignore any bits referring to the
  4. #    traffic lights, etc.
  5. #
  6. ------------------------------------------------------------------------------*/
  7.  
  8.  
  9. #include <Values.h>
  10. #include <Types.h>
  11. #include <Resources.h>
  12. #include <QuickDraw.h>
  13. #include <Fonts.h>
  14. #include <Events.h>
  15. #include <Windows.h>
  16. #include <Menus.h>
  17. #include <TextEdit.h>
  18. #include <Dialogs.h>
  19. #include <Desk.h>
  20. #include <ToolUtils.h>
  21. #include <Memory.h>
  22. #include <SegLoad.h>
  23. #include <Files.h>
  24. #include <OSUtils.h>
  25. #include <OSEvents.h>
  26. #include <DiskInit.h>
  27. #include <Packages.h>
  28. #include <Traps.h>
  29. #include <Sample.h>        /* bring in all the #defines for Sample */
  30.  
  31. #include "Password.h"
  32.  
  33. /* The "g" prefix is used to emphasize that a variable is global. */
  34.  
  35. /* GMac is used to hold the result of a SysEnvirons call. This makes
  36.    it convenient for any routine to check the environment. */
  37. SysEnvRec    gMac;                /* set up by Initialize */
  38.  
  39. /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  40.    trap is available. If it is false, we know that we must call GetNextEvent. */
  41. Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  42.  
  43. /* GInBackground is maintained by our osEvent handling routines. Any part of
  44.    the program can check it to find out if it is currently in the background. */
  45. Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  46.  
  47.  
  48. /* The following globals are the state of the window. If we supported more than
  49.    one window, they would be attatched to each document, rather than globals. */
  50.  
  51. /* Here are declarations for all of the C routines. In MPW 3.0 we can use
  52.    actual prototypes for parameter type checking. */
  53. void EventLoop( void );
  54. void DoEvent( EventRecord *event );
  55. void AdjustCursor( Point mouse, RgnHandle region );
  56. void GetGlobalMouse( Point *mouse );
  57. void DoUpdate( WindowPtr window );
  58. void DoActivate( WindowPtr window, Boolean becomingActive );
  59. void DoContentClick( WindowPtr window );
  60. void DrawWindow( WindowPtr window );
  61. void AdjustMenus( void );
  62. void DoMenuCommand( long menuResult );
  63. void SetLight( WindowPtr window, Boolean newStopped );
  64. Boolean DoCloseWindow( WindowPtr window );
  65. void Terminate( void );
  66. void Initialize( void );
  67. Boolean GoGetRect( short rectID, Rect *theRect );
  68. void ForceEnvirons( void );
  69. Boolean IsAppWindow( WindowPtr window );
  70. Boolean IsDAWindow( WindowPtr window );
  71. Boolean TrapAvailable( short tNumber, TrapType tType );
  72. void AlertUser( void );
  73.  
  74.  
  75. /* Define HiWrd and LoWrd macros for efficiency. */
  76. #define HiWrd(aLong)    (((aLong) >> 16) & 0xFFFF)
  77. #define LoWrd(aLong)    ((aLong) & 0xFFFF)
  78.  
  79. /* Define TopLeft and BotRight macros for convenience. Notice the implicit
  80.    dependency on the ordering of fields within a Rect */
  81. #define TopLeft(aRect)    (* (Point *) &(aRect).top)
  82. #define BotRight(aRect)    (* (Point *) &(aRect).bottom)
  83.  
  84.  
  85. extern void _DataInit();
  86.  
  87. /* This routine is part of the MPW runtime library. This external
  88.    reference to it is done so that we can unload its segment, %A5Init. */
  89.  
  90.  
  91. #pragma segment Main
  92. main()
  93. {
  94.     UnloadSeg((Ptr) _DataInit);        /* note that _DataInit must not be in Main! */
  95.     
  96.     /* 1.01 - call to ForceEnvirons removed */
  97.     
  98.     /*    If you have stack requirements that differ from the default,
  99.         then you could use SetApplLimit to increase StackSpace at 
  100.         this point, before calling MaxApplZone. */
  101.     MaxApplZone();                    /* expand the heap so code segments load at the top */
  102.  
  103.     Initialize();                    /* initialize the program */
  104.     UnloadSeg((Ptr) Initialize);    /* note that Initialize must not be in Main! */
  105.  
  106.     EventLoop();                    /* call the main event loop */
  107. }
  108.  
  109.  
  110. /*    Get events forever, and handle them by calling DoEvent.
  111.     Get the events by calling WaitNextEvent, if it's available, otherwise
  112.     by calling GetNextEvent. Also call AdjustCursor each time through the loop. */
  113.  
  114. #pragma segment Main
  115. void EventLoop()
  116. {
  117.     RgnHandle    cursorRgn;
  118.     Boolean        gotEvent;
  119.     EventRecord    event;
  120.     Point        mouse;
  121.  
  122.     cursorRgn = NewRgn();            /* we’ll pass WNE an empty region the 1st time thru */
  123.     do {
  124.         /* use WNE if it is available */
  125.         if ( gHasWaitNextEvent ) {
  126.             GetGlobalMouse(&mouse);
  127.             AdjustCursor(mouse, cursorRgn);
  128.             gotEvent = WaitNextEvent(everyEvent, &event, MAXLONG, cursorRgn);
  129.         }
  130.         else {
  131.             SystemTask();
  132.             gotEvent = GetNextEvent(everyEvent, &event);
  133.         }
  134.         if ( gotEvent ) {
  135.             /* make sure we have the right cursor before handling the event */
  136.             AdjustCursor(event.where, cursorRgn);
  137.             DoEvent(&event);
  138.         }
  139.         /*    If you are using modeless dialogs that have editText items,
  140.             you will want to call IsDialogEvent to give the caret a chance
  141.             to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  142.             for a non-NIL value before calling IsDialogEvent. */
  143.     } while ( true );    /* loop forever; we quit via ExitToShell */
  144. } /*EventLoop*/
  145.  
  146.  
  147. /* Do the right thing for an event. Determine what kind of event it is, and call
  148.  the appropriate routines. */
  149.  
  150. #pragma segment Main
  151. void DoEvent(event)
  152.     EventRecord    *event;
  153. {
  154.     short        part, err;
  155.     WindowPtr    window;
  156.     Boolean        hit;
  157.     char        key;
  158.     Point        aPoint;
  159.  
  160.     switch ( event->what ) {
  161.         case mouseDown:
  162.             part = FindWindow(event->where, &window);
  163.             switch ( part ) {
  164.                 case inMenuBar:                /* process a mouse menu command (if any) */
  165.                     AdjustMenus();
  166.                     DoMenuCommand(MenuSelect(event->where));
  167.                     break;
  168.                 case inSysWindow:            /* let the system handle the mouseDown */
  169.                     SystemClick(event, window);
  170.                     break;
  171.                 case inContent:
  172.                     if ( window != FrontWindow() ) {
  173.                         SelectWindow(window);
  174.                         /*DoEvent(event);*/    /* use this line for "do first click" */
  175.                     } else
  176.                         DoContentClick(window);
  177.                     break;
  178.                 case inDrag:                /* pass screenBits.bounds to get all gDevices */
  179.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  180.                     break;
  181.                 case inGrow:
  182.                     break;
  183.                 case inZoomIn:
  184.                 case inZoomOut:
  185.                     hit = TrackBox(window, event->where, part);
  186.                     if ( hit ) {
  187.                         SetPort(window);                /* the window must be the current port... */
  188.                         EraseRect(&window->portRect);    /* because of a bug in ZoomWindow */
  189.                         ZoomWindow(window, part, true);    /* note that we invalidate and erase... */
  190.                         InvalRect(&window->portRect);    /* to make things look better on-screen */
  191.                     }
  192.                     break;
  193.             }
  194.             break;
  195.         case keyDown:
  196.         case autoKey:                        /* check for menukey equivalents */
  197.             key = event->message & charCodeMask;
  198.             if ( event->modifiers & cmdKey )            /* Command key down */
  199.                 if ( event->what == keyDown ) {
  200.                     AdjustMenus();                        /* enable/disable/check menu items properly */
  201.                     DoMenuCommand(MenuKey(key));
  202.                 }
  203.             break;
  204.         case activateEvt:
  205.             DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  206.             break;
  207.         case updateEvt:
  208.             DoUpdate((WindowPtr) event->message);
  209.             break;
  210.         /*    1.01 - It is not a bad idea to at least call DIBadMount in response
  211.             to a diskEvt, so that the user can format a floppy. */
  212.         case diskEvt:
  213.             if ( HiWord(event->message) != noErr ) {
  214.                 SetPt(&aPoint, kDILeft, kDITop);
  215.                 err = DIBadMount(aPoint, event->message);
  216.             }
  217.             break;
  218.         case kOSEvent:
  219.         /*    1.02 - must BitAND with 0x0FF to get only low byte */
  220.             switch ((event->message >> 24) & 0x0FF) {        /* high byte of message */
  221.                 case kSuspendResumeMessage:        /* suspend/resume is also an activate/deactivate */
  222.                     gInBackground = (event->message & kResumeMask) == 0;
  223.                     DoActivate(FrontWindow(), !gInBackground);
  224.                     break;
  225.             }
  226.             break;
  227.     }
  228. } /*DoEvent*/
  229.  
  230.  
  231. /*    Change the cursor's shape, depending on its position. This also calculates the region
  232.     where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  233.     that region, an event would be generated, causing this routine to be called,
  234.     allowing us to change the region to the region the mouse is currently in. If
  235.     there is more to the event than just “the mouse moved”, we get called before the
  236.     event is processed to make sure the cursor is the right one. In any (ahem) event,
  237.     this is called again before we     fall back into WNE. */
  238.  
  239. #pragma segment Main
  240. void AdjustCursor(mouse,region)
  241.     Point        mouse;
  242.     RgnHandle    region;
  243. {
  244.     WindowPtr    window;
  245.     RgnHandle    arrowRgn;
  246.     RgnHandle    plusRgn;
  247.     Rect        globalPortRect;
  248.  
  249.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  250.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  251.         /* calculate regions for different cursor shapes */
  252.         arrowRgn = NewRgn();
  253.         plusRgn = NewRgn();
  254.  
  255.         /* start with a big, big rectangular region */
  256.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
  257.  
  258.         /* calculate plusRgn */
  259.         if ( IsAppWindow(window) ) {
  260.             SetPort(window);    /* make a global version of the viewRect */
  261.             SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
  262.             globalPortRect = window->portRect;
  263.             RectRgn(plusRgn, &globalPortRect);
  264.             SectRgn(plusRgn, window->visRgn, plusRgn);
  265.             SetOrigin(0, 0);
  266.         }
  267.  
  268.         /* subtract other regions from arrowRgn */
  269.         DiffRgn(arrowRgn, plusRgn, arrowRgn);
  270.  
  271.         /* change the cursor and the region parameter */
  272.         if ( PtInRgn(mouse, plusRgn) ) {
  273.             SetCursor(*GetCursor(plusCursor));
  274.             CopyRgn(plusRgn, region);
  275.         } else {
  276.             SetCursor(&qd.arrow);
  277.             CopyRgn(arrowRgn, region);
  278.         }
  279.  
  280.         /* get rid of our local regions */
  281.         DisposeRgn(arrowRgn);
  282.         DisposeRgn(plusRgn);
  283.     }
  284. } /*AdjustCursor*/
  285.  
  286.  
  287. /*    Get the global coordinates of the mouse. When you call OSEventAvail
  288.     it will return either a pending event or a null event. In either case,
  289.     the where field of the event record will contain the current position
  290.     of the mouse in global coordinates and the modifiers field will reflect
  291.     the current state of the modifiers. Another way to get the global
  292.     coordinates is to call GetMouse and LocalToGlobal, but that requires
  293.     being sure that thePort is set to a valid port. */
  294.  
  295. #pragma segment Main
  296. void GetGlobalMouse(mouse)
  297.     Point    *mouse;
  298. {
  299.     EventRecord    event;
  300.     
  301.     OSEventAvail(kNoEvents, &event);    /* we aren't interested in any events */
  302.     *mouse = event.where;                /* just the mouse position */
  303. } /*GetGlobalMouse*/
  304.  
  305.  
  306. /*    This is called when an update event is received for a window.
  307.     It calls DrawWindow to draw the contents of an application window.
  308.     As an efficiency measure that does not have to be followed, it
  309.     calls the drawing routine only if the visRgn is non-empty. This
  310.     will handle situations where calculations for drawing or drawing
  311.     itself is very time-consuming. */
  312.  
  313. #pragma segment Main
  314. void DoUpdate(window)
  315.     WindowPtr    window;
  316. {
  317.     if ( IsAppWindow(window) ) {
  318.         BeginUpdate(window);                /* this sets up the visRgn */
  319.         if ( ! EmptyRgn(window->visRgn) )    /* draw if updating needs to be done */
  320.             DrawWindow(window);
  321.         EndUpdate(window);
  322.     }
  323. } /*DoUpdate*/
  324.  
  325.  
  326. /*    This is called when a window is activated or deactivated.
  327.     In Sample, the Window Manager's handling of activate and
  328.     deactivate events is sufficient. Other applications may have
  329.     TextEdit records, controls, lists, etc., to activate/deactivate. */
  330.  
  331. #pragma segment Main
  332. void DoActivate(window, becomingActive)
  333.     WindowPtr    window;
  334.     Boolean        becomingActive;
  335. {
  336.     if ( IsAppWindow(window) ) {
  337.         if ( becomingActive )
  338.             /* do whatever you need to at activation */ ;
  339.         else
  340.             /* do whatever you need to at deactivation */ ;
  341.     }
  342. } /*DoActivate*/
  343.  
  344.  
  345. /*    This is called when a mouse-down event occurs in the content of a window.
  346.     Other applications might want to call FindControl, TEClick, etc., to
  347.     further process the click. */
  348.  
  349. #pragma segment Main
  350. void DoContentClick(window)
  351.     WindowPtr    window;
  352. {
  353. #pragma unused (window)
  354. } /*DoContentClick*/
  355.  
  356.  
  357. /* Draw the contents of the application window. We do some drawing in color, using
  358.    Classic QuickDraw's color capabilities. This will be black and white on old
  359.    machines, but color on color machines. At this point, the window’s visRgn
  360.    is set to allow drawing only where it needs to be done. */
  361.  
  362. #pragma segment Main
  363. void DrawWindow(window)
  364.     WindowPtr    window;
  365. {
  366.     SetPort(window);
  367.  
  368.     EraseRect(&window->portRect);    /* clear out any garbage that may linger */
  369. } /*DrawWindow*/
  370.  
  371.  
  372. /*    Enable and disable menus based on the current state.
  373.     The user can only select enabled menu items. We set up all the menu items
  374.     before calling MenuSelect or MenuKey, since these are the only times that
  375.     a menu item can be selected. Note that MenuSelect is also the only time
  376.     the user will see menu items. This approach to deciding what enable/
  377.     disable state a menu item has the advantage of concentrating all
  378.     the decision-making in one routine, as opposed to being spread throughout
  379.     the application. Other application designs may take a different approach
  380.     that is just as valid. */
  381.  
  382. #pragma segment Main
  383. void AdjustMenus()
  384. {
  385.     WindowPtr    window;
  386.     MenuHandle    menu;
  387.  
  388.     window = FrontWindow();
  389.  
  390.     menu = GetMHandle(mFile);
  391.     if ( IsDAWindow(window) )        /* we can allow desk accessories to be closed from the menu */
  392.         EnableItem(menu, iClose);
  393.     else
  394.         DisableItem(menu, iClose);    /* but not our traffic light window */
  395.  
  396.     menu = GetMHandle(mEdit);
  397.     if ( IsDAWindow(window) ) {        /* a desk accessory might need the edit menu… */
  398.         EnableItem(menu, iUndo);
  399.         EnableItem(menu, iCut);
  400.         EnableItem(menu, iCopy);
  401.         EnableItem(menu, iClear);
  402.         EnableItem(menu, iPaste);
  403.     } else {                        /* …but we don’t use it */
  404.         DisableItem(menu, iUndo);
  405.         DisableItem(menu, iCut);
  406.         DisableItem(menu, iCopy);
  407.         DisableItem(menu, iClear);
  408.         DisableItem(menu, iPaste);
  409.     }
  410.     
  411.     menu = GetMHandle(mPassword);
  412.         EnableItem(menu, iTwoItem);
  413.         EnableItem(menu, iDifferentFont);
  414.         EnableItem(menu, iInternalBuffer);
  415.     
  416. } /*AdjustMenus*/
  417.  
  418.  
  419. /*    This is called when an item is chosen from the menu bar (after calling
  420.     MenuSelect or MenuKey). It performs the right operation for each command.
  421.     It is good to have both the result of MenuSelect and MenuKey go to
  422.     one routine like this to keep everything organized. */
  423.  
  424. #pragma segment Main
  425. void DoMenuCommand(menuResult)
  426.     long        menuResult;
  427. {
  428.     short        menuID;                /* the resource ID of the selected menu */
  429.     short        menuItem;            /* the item number of the selected menu */
  430.     short        itemHit;
  431.     Str255        daName;
  432.     short        daRefNum;
  433.     Boolean        handledByDA;
  434.  
  435.     menuID = HiWord(menuResult);    /* use macros for efficiency to... */
  436.     menuItem = LoWord(menuResult);    /* get menu item number and menu number */
  437.     switch ( menuID ) {
  438.         case mApple:
  439.             switch ( menuItem ) {
  440.                 case iAbout:        /* bring up alert for About */
  441.                     itemHit = Alert(rAboutAlert, nil);
  442.                     break;
  443.                 default:            /* all non-About items in this menu are DAs */
  444.                     /* type Str255 is an array in MPW 3 */
  445.                     GetItem(GetMHandle(mApple), menuItem, daName);
  446.                     daRefNum = OpenDeskAcc(daName);
  447.                     break;
  448.             }
  449.             break;
  450.         case mFile:
  451.             switch ( menuItem ) {
  452.                 case iClose:
  453.                     DoCloseWindow(FrontWindow());
  454.                     break;
  455.                 case iQuit:
  456.                     Terminate();
  457.                     break;
  458.             }
  459.             break;
  460.         case mEdit:                    /* call SystemEdit for DA editing & MultiFinder */
  461.             handledByDA = SystemEdit(menuItem-1);    /* since we don’t do any Editing */
  462.             break;
  463.         case mPassword:
  464.             switch ( menuItem ) {
  465.                 case iTwoItem:
  466.                     DisplayPassword(TwoItemDialog());
  467.                     break;
  468.                 case iDifferentFont:
  469.                     DisplayPassword(DifferentFontDialog());
  470.                     break;
  471.                 case iInternalBuffer:
  472.                     DisplayPassword(InternalBufferDialog());
  473.                     break;
  474.             }
  475.             break;
  476.     }
  477.     HiliteMenu(0);                    /* unhighlight what MenuSelect (or MenuKey) hilited */
  478. } /*DoMenuCommand*/
  479.  
  480.  
  481. /* Close a window. This handles desk accessory and application windows. */
  482.  
  483. /*    1.01 - At this point, if there was a document associated with a
  484.     window, you could do any document saving processing if it is 'dirty'.
  485.     DoCloseWindow would return true if the window actually closed, i.e.,
  486.     the user didn’t cancel from a save dialog. This result is handy when
  487.     the user quits an application, but then cancels the save of a document
  488.     associated with a window. */
  489.  
  490. #pragma segment Main
  491. Boolean DoCloseWindow(window)
  492.     WindowPtr    window;
  493. {
  494.     if ( IsDAWindow(window) )
  495.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  496.     else if ( IsAppWindow(window) )
  497.         CloseWindow(window);
  498.     return true;
  499. } /*DoCloseWindow*/
  500.  
  501.  
  502. /**************************************************************************************
  503. *** 1.01 DoCloseBehind(window) was removed ***
  504.  
  505.     1.01 - DoCloseBehind was a good idea for closing windows when quitting
  506.     and not having to worry about updating the windows, but it suffered
  507.     from a fatal flaw. If a desk accessory owned two windows, it would
  508.     close both those windows when CloseDeskAcc was called. When DoCloseBehind
  509.     got around to calling DoCloseWindow for that other window that was already
  510.     closed, things would go very poorly. Another option would be to have a
  511.     procedure, GetRearWindow, that would go through the window list and return
  512.     the last window. Instead, we decided to present the standard approach
  513.     of getting and closing FrontWindow until FrontWindow returns NIL. This
  514.     has a potential benefit in that the window whose document needs to be saved
  515.     may be visible since it is the front window, therefore decreasing the
  516.     chance of user confusion. For aesthetic reasons, the windows in the
  517.     application should be checked for updates periodically and have the
  518.     updates serviced.
  519. **************************************************************************************/
  520.  
  521.  
  522. /* Clean up the application and exit. We close all of the windows so that
  523.  they can update their documents, if any. */
  524.  
  525. /*    1.01 - If we find out that a cancel has occurred, we won't exit to the
  526.     shell, but will return instead. */
  527.  
  528. #pragma segment Main
  529. void Terminate()
  530. {
  531.     WindowPtr    aWindow;
  532.     Boolean        closed;
  533.     
  534.     closed = true;
  535.     do {
  536.         aWindow = FrontWindow();                /* get the current front window */
  537.         if (aWindow != nil)
  538.             closed = DoCloseWindow(aWindow);    /* close this window */    
  539.     }
  540.     while (closed && (aWindow != nil));
  541.     if (closed)
  542.         ExitToShell();                            /* exit if no cancellation */
  543. } /*Terminate*/
  544.  
  545.  
  546. /*    Set up the whole world, including global variables, Toolbox managers,
  547.     and menus. We also create our one application window at this time.
  548.     Since window storage is non-relocateable, how and when to allocate space
  549.     for windows is very important so that heap fragmentation does not occur.
  550.     Because Sample has only one window and it is only disposed when the application
  551.     quits, we will allocate its space here, before anything that might be a locked
  552.     relocatable object gets into the heap. This way, we can force the storage to be
  553.     in the lowest memory available in the heap. Window storage can differ widely
  554.     amongst applications depending on how many windows are created and disposed. */
  555.  
  556. /*    1.01 - The code that used to be part of ForceEnvirons has been moved into
  557.     this module. If an error is detected, instead of merely doing an ExitToShell,
  558.     which leaves the user without much to go on, we call AlertUser, which puts
  559.     up a simple alert that just says an error occurred and then calls ExitToShell.
  560.     Since there is no other cleanup needed at this point if an error is detected,
  561.     this form of error- handling is acceptable. If more sophisticated error recovery
  562.     is needed, an exception mechanism, such as is provided by Signals, can be used. */
  563.  
  564. #pragma segment Initialize
  565. void Initialize()
  566. {    Handle        menuBar;
  567.     long        total, contig;
  568.     EventRecord event;
  569.     short        count;
  570.  
  571.     gInBackground = false;
  572.  
  573.     InitGraf((Ptr) &qd.thePort);
  574.     InitFonts();
  575.     InitWindows();
  576.     InitMenus();
  577.     TEInit();
  578.     InitDialogs(nil);
  579.     InitCursor();
  580.     
  581.     /*    Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  582.          if you are using it. */
  583.     /*    NOTE -- It is no longer necessary, and actually unhealthy, to check
  584.         PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  585.         of checking for port availability themselves. */
  586.     
  587.     /*    This next bit of code is necessary to allow the default button of our
  588.         alert be outlined.
  589.         1.02 - Changed to call EventAvail so that we don't lose some important
  590.         events. */
  591.      
  592.     for (count = 1; count <= 3; count++)
  593.         EventAvail(everyEvent, &event);
  594.     
  595.     /*    Ignore the error returned from SysEnvirons; even if an error occurred,
  596.         the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  597.         call to SysEnvirons by calling it after initializing AppleTalk. */
  598.      
  599.     SysEnvirons(kSysEnvironsVersion, &gMac);
  600.     
  601.     /* Make sure that the machine has at least 128K ROMs. If it doesn't, exit. */
  602.     
  603.     if (gMac.machineType < 0) AlertUser();
  604.     
  605.     /*    1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  606.         in TrapAvailable if a tool trap value is out of range. */
  607.         
  608.     gHasWaitNextEvent = TrapAvailable(_WaitNextEvent, ToolTrap);
  609.  
  610.     /*    1.01 - We used to make a check for memory at this point by examining ApplLimit,
  611.         ApplicZone, and StackSpace and comparing that to the minimum size we told
  612.         MultiFinder we needed. This did not work well because it assumed too much about
  613.         the relationship between what we asked MultiFinder for and what we would actually
  614.         get back, as well as how to measure it. Instead, we will use an alternate
  615.         method comprised of two steps. */
  616.      
  617.     /*    It is better to first check the size of the application heap against a value
  618.         that you have determined is the smallest heap the application can reasonably
  619.         work in. This number should be derived by examining the size of the heap that
  620.         is actually provided by MultiFinder when the minimum size requested is used.
  621.         The derivation of the minimum size requested from MultiFinder is described
  622.         in Sample.h. The check should be made because the preferred size can end up
  623.         being set smaller than the minimum size by the user. This extra check acts to
  624.         insure that your application is starting from a solid memory foundation. */
  625.      
  626.     if ((long) GetApplLimit() - (long) ApplicZone() < kMinHeap) AlertUser();
  627.     
  628.     /*    Next, make sure that enough memory is free for your application to run. It
  629.         is possible for a situation to arise where the heap may have been of required
  630.         size, but a large scrap was loaded which left too little memory. To check for
  631.         this, call PurgeSpace and compare the result with a value that you have determined
  632.         is the minimum amount of free memory your application needs at initialization.
  633.         This number can be derived several different ways. One way that is fairly
  634.         straightforward is to run the application in the minimum size configuration
  635.         as described previously. Call PurgeSpace at initialization and examine the value
  636.         returned. However, you should make sure that this result is not being modified
  637.         by the scrap's presence. You can do that by calling ZeroScrap before calling
  638.         PurgeSpace. Make sure to remove that call before shipping, though. */
  639.     
  640.     /* ZeroScrap(); */
  641.  
  642.     PurgeSpace(&total, &contig);
  643.     if (total < kMinSpace) AlertUser();
  644.  
  645.     /*    The extra benefit to waiting until after the Toolbox Managers have been initialized
  646.         to check memory is that we can now give the user an alert to tell him/her what
  647.         happened. Although it is possible that the memory situation could be worsened by
  648.         displaying an alert, MultiFinder would gracefully exit the application with
  649.         an informative alert if memory became critical. Here we are acting more
  650.         in a preventative manner to avoid future disaster from low-memory problems. */
  651.  
  652.     menuBar = GetNewMBar(rMenuBar);            /* read menus into menu bar */
  653.     if ( menuBar == nil ) AlertUser();
  654.     SetMenuBar(menuBar);                    /* install menus */
  655.     DisposHandle(menuBar);
  656.     AddResMenu(GetMHandle(mApple), 'DRVR');    /* add DA names to Apple menu */
  657.     DrawMenuBar();
  658.     
  659. } /*Initialize*/
  660.  
  661. /*    Check to see if a window belongs to the application. If the window pointer
  662.     passed was NIL, then it could not be an application window. WindowKinds
  663.     that are negative belong to the system and windowKinds less than userKind
  664.     are reserved by Apple except for windowKinds equal to dialogKind, which
  665.     mean it is a dialog.
  666.     1.02 - In order to reduce the chance of accidentally treating some window
  667.     as an AppWindow that shouldn't be, we'll only return true if the windowkind
  668.     is userKind. If you add different kinds of windows to Sample you'll need
  669.     to change how this all works. */
  670.  
  671. #pragma segment Main
  672. Boolean IsAppWindow(window)
  673.     WindowPtr    window;
  674. {
  675.     short        windowKind;
  676.  
  677.     if ( window == nil )
  678.         return false;
  679.     else {    /* application windows have windowKinds = userKind (8) */
  680.         windowKind = ((WindowPeek) window)->windowKind;
  681.         return ( windowKind == userKind );
  682.     }
  683. } /*IsAppWindow*/
  684.  
  685.  
  686. /* Check to see if a window belongs to a desk accessory. */
  687.  
  688. #pragma segment Main
  689. Boolean IsDAWindow(window)
  690.     WindowPtr    window;
  691. {
  692.     if ( window == nil )
  693.         return false;
  694.     else    /* DA windows have negative windowKinds */
  695.         return ( ((WindowPeek) window)->windowKind < 0 );
  696. } /*IsDAWindow*/
  697.  
  698.  
  699. /*    Check to see if a given trap is implemented. This is only used by the
  700.     Initialize routine in this program, so we put it in the Initialize segment.
  701.     The recommended approach to see if a trap is implemented is to see if
  702.     the address of the trap routine is the same as the address of the
  703.     Unimplemented trap. */
  704. /*    1.02 - Needs to be called after call to SysEnvirons so that it can check
  705.     if a ToolTrap is out of range of a pre-MacII ROM. */
  706.  
  707. #pragma segment Initialize
  708. Boolean TrapAvailable(tNumber,tType)
  709.     short        tNumber;
  710.     TrapType    tType;
  711. {
  712.     if ( ( tType == ToolTrap ) &&
  713.         ( gMac.machineType > envMachUnknown ) &&
  714.         ( gMac.machineType < envMacII ) ) {        /* it's a 512KE, Plus, or SE */
  715.         tNumber = tNumber & 0x03FF;
  716.         if ( tNumber > 0x01FF )                    /* which means the tool traps */
  717.             tNumber = _Unimplemented;            /* only go to 0x01FF */
  718.     }
  719.     return NGetTrapAddress(tNumber, tType) != GetTrapAddress(_Unimplemented);
  720. } /*TrapAvailable*/
  721.  
  722.  
  723. /*    Display an alert that tells the user an error occurred, then exit the program.
  724.     This routine is used as an ultimate bail-out for serious errors that prohibit
  725.     the continuation of the application. Errors that do not require the termination
  726.     of the application should be handled in a different manner. Error checking and
  727.     reporting has a place even in the simplest application. The error number is used
  728.     to index an 'STR#' resource so that a relevant message can be displayed. */
  729.  
  730. #pragma segment Main
  731. void AlertUser()
  732. {
  733.     short        itemHit;
  734.  
  735.     SetCursor(&qd.arrow);
  736.     itemHit = Alert(rUserAlert, nil);
  737.     ExitToShell();
  738. } /* AlertUser */